using System;
using System.Collections.Generic;
using System.Linq;

namespace ToDictionary
{
    public static class StringExtensions
    {
        public static IDictionary<string, string> ToDictionary(string config)
        {
            return new Configuration {Value = config}
                .SplitIntoSettings()
                .SplitIntoPVs()
                .CreateDict();
        }

        internal static IEnumerable<Setting> SplitIntoSettings(this Configuration config)
        {
            if (config == null)
                throw new ArgumentNullException("config");

            var splitSettings = config.Value.Split(new[] {";"}, StringSplitOptions.RemoveEmptyEntries);
            return splitSettings.Select(current => new Setting {Value = current});
        }

        internal static IEnumerable<ParamValuePair> SplitIntoPVs(this IEnumerable<Setting> settings)
        {
            return settings.Select(setting => SplitIntoPVs(setting));
        }

        private static ParamValuePair SplitIntoPVs(this Setting setting)
        {
            var splitValues = setting.Value.Split(new[] {'='}, 2);

            string param = splitValues[0].Trim();
            if (string.IsNullOrEmpty(param))
                throw new ArgumentException("Empty parameter are not allowed.");

            string value = splitValues.Length > 1 ? splitValues[1] : string.Empty;
            return new ParamValuePair(param, value);
        }

        internal static IDictionary<string, string> CreateDict(this IEnumerable<ParamValuePair> paramValues)
        {
            return paramValues.ToDictionary(current => current.Param, paramValue => paramValue.Value);
        }
    }
}